using System.Windows;
using System.Windows.Controls;

namespace 雷赛板卡上位机.Utilities
{
    public static class TextBoxExtensions
    {
        // 修正依赖属性类型和元数据
        public static readonly DependencyProperty ScrollToEndProperty =
            DependencyProperty.RegisterAttached(
                "ScrollToEnd",
                typeof(bool),
                typeof(TextBoxExtensions),
                new PropertyMetadata(false, OnScrollToEndChanged));

        public static bool GetScrollToEnd(DependencyObject obj)
        {
            return (bool)obj.GetValue(ScrollToEndProperty);
        }

        public static void SetScrollToEnd(DependencyObject obj, bool value)
        {
            obj.SetValue(ScrollToEndProperty, value);
        }

        // 修正事件处理逻辑
        private static void OnScrollToEndChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var textBox = d as TextBox;
            if (textBox == null) return;

            bool enableScroll = (bool)e.NewValue;

            if (enableScroll)
            {
                // 启用自动滚动：订阅 TextChanged 事件
                textBox.TextChanged += OnTextChanged;
            }
            else
            {
                // 禁用自动滚动：移除事件订阅
                textBox.TextChanged -= OnTextChanged;
            }
        }

        // 文本变化时滚动到底部
        private static void OnTextChanged(object sender, EventArgs e)
        {
            var textBox = sender as TextBox;
            if (textBox != null)
            {
                textBox.ScrollToEnd();
            }
        }
    }
}